import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class TCPClient {

    private String ip;
    private int port;

    private Socket mSocket;
    private SocketAddress mSocketAddress;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;
    private boolean _isConnected = false;


    public TCPClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }


    public void connect() {
        try {
            this.mSocket = new Socket();
            this.mSocket.setKeepAlive(true);
            this.mSocketAddress = new InetSocketAddress(ip, port);
            this.mSocket.connect( mSocketAddress, 3000);// 设置连接超时时间为3秒

            this.mOutputStream = mSocket.getOutputStream();
            this.mInputStream = mSocket.getInputStream();

            this.mReadThread = new TCPClient.ReadThread();
            this.mReadThread.start();
            this._isConnected = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {

        if (this.mReadThread != null) {
            this.mReadThread.interrupt();
        }
        if (this.mSocket != null) {
            try {
                this.mSocket.close();
                this.mSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        this._isConnected = false;
    }

    public boolean isConnected() {
        return this._isConnected;
    }


    public void send(byte[] bOutArray) {
        try {
            this.mOutputStream.write(bOutArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected abstract void onDataReceive(byte[] bytes, int size);

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    if (TCPClient.this.mInputStream == null) {
                        return;
                    }
                    int available = TCPClient.this.mInputStream.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = TCPClient.this.mInputStream.read(buffer);
                        if (size > 0) {
                            onDataReceive(buffer, size);
                        }
                    } else {
                        Thread.sleep(50);
                    }


                } catch (Throwable e) {
                    System.out.println(e.getMessage());
                    return;
                }
            }
        }
    }
}

//// TCP 通信
//        tcpClient = new TCPClient("192.168.0.110", 10000) {
//@Override
//protected void onDataReceive(byte[] bytes, int size) {
////                String content = "TCPServer say :" + new String(bytes, 0, size);
//        }
//        };
//        tcpClient.connect();//连接TCPServe
//        if (tcpClient.isConnected()) {
//        tcpClient.send(upLoadData(1,2,3,4,5,6));
//        }
    /**
     * 封装成http
     * @param temperature
     * @param humidity
     * @param negaticeO2Ion
     * @param pm25
     * @param pm10
     * @param db
     * @return
     */
//    private static byte[] upLoadData(float temperature, float humidity, float negaticeO2Ion, float pm25, float pm10, float db) {
//        Date dNow = new Date( );
//        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
//        String dataStr = "{\"temperature\":"+String.format("%.1f",temperature)+",\"humidity\":"+String.format("%.1f",humidity)+",\"negaticeO2Ion\":"+String.format("%.1f",negaticeO2Ion)+",\"pm25\":"+String.format("%.1f",pm25)+",\"pm10\":"+String.format("%.1f",pm10)+",\"db\":"+String.format("%.1f",db)+",\"collect_time\":"+ft.format(dNow)+"}";
//        //发送数据
//        String upToHttpContent = "POST /api/environment/id/recordUpload HTTP/1.1\n" +
//                "Content-Type: text/plain\n" +
//                "User-Agent: PostmanRuntime/7.28.1\n" +
//                "Accept: */*\n" +
//                "Postman-Token: bb1e2ba7-673e-4917-b84a-705e85a94b6f\n" +
//                "Host: "+HTTP_SERVER+"\n" +
//                "Accept-Encoding: gzip, deflate, br\n" +
//                "Connection: keep-alive\n" +
//                "Content-Length: "+dataStr.length()+"\n" +
//                "\n" +dataStr;
//        return upToHttpContent.getBytes();
//    }
